package cmd

import (
	"fmt"
	_ "gitee.com/igolang/imoney/internal/app"
	"gitee.com/igolang/imoney/internal/core"
	"gitee.com/igolang/pkg/boot"
	"github.com/spf13/cobra"
	"os"
	"os/signal"
)

var (
	httpPort int
)

var httpCmd = &cobra.Command{
	Use:     "http",
	Short:   "http server",
	Long:    "启动HTTP服务，详见参数",
	Example: "go run main.go http -p 3000",
	PreRun: func(cmd *cobra.Command, args []string) {
		// 设置运行模式
		boot.RunMode = boot.ModeHttp
		// 初始化各种东西
		core.AddService(core.Http(getHttpAddr()))
		core.Init()
	},
	Run: func(cmd *cobra.Command, args []string) {
		ch := make(chan os.Signal, 1)
		signal.Notify(ch, sigs...)
		for {
			select {
			case sig := <-ch:
				log.Printf("pid[%d]: server shutting down by signal: %v\n", boot.Pid, sig)
				return
			}
		}
	},
	PostRun: func(cmd *cobra.Command, args []string) {
		core.Shutdown()
		log.Printf("pid[%d]: all servers shutdown", boot.Pid)
		os.Exit(0)
	},
}

func getHttpAddr() string {
	if httpPort > 0 {
		return fmt.Sprintf(":%d", httpPort)
	}

	return ""
}

func init() {
	httpCmd.PersistentFlags().IntVarP(&httpPort, "port", "p", 0, "设置HTTP服务监听端口")
}
